<?php

class Controller_Admin_Users extends Controller_Admin_Template
{

	protected $template = 'admin/template';

	public function before()
	{
		parent::before();
		$this->model = Model::factory('users');
	}

	public function actionIndex()
	{
//		$this->addScript('/scripts/jquery/jquery.js');
		$this->addScript('/scripts/jquery/tablefilter/table.filter.js');
		$this->template->title = 'User management';
		$this->template->content = new View('admin/users/list');
        $users=$this->model->getUsers();
        unset($users[1]);
		$this->template->content->users =$users;
	}

	public function actionAdd()
	{
		$this->template->title = 'Add user';
		$this->actionEdit();
	}

	public function actionEdit($id = null)
	{
		if ($id) {
			$this->template->title = 'Edit user profile';
			$form = new Form('user');
		} else {
			$form = new Form('user');
		}
		$form->attributes['autocomplete'] = 'off';
		$form->labelWidth = '150px';
		$form->text('fullName', 'Full name')->attribute('size', 32)
			->rule('maxLength', 64)->rule('required');
		$form->text('email', 'E-mail')->attribute('size', 32)
			->rule('maxLength', 64)->rule('email')->rule('required')
			->callback('emailCheck', array('id' => $id));
		function emailCheck($field, $args) {
			extract($args);
			if (Model::factory('users')->exists($field->value, $id)) {
				$field->error(Text::DUPLICATE_KEY);
			}
		}
		$form->text('name', 'Login')->rule('alias')->attribute('size', 24)
			->attribute('maxlength', 16)->rule('required')
			->callback('usernameCheck', array('id' => $id));
		function usernameCheck($field, $args) {
			extract($args);
			if (0 == preg_match('/^[a-z0-9-]+$/ui', $field->value)) {
				$field->error('Only letters, numbers and `-` are allowed');
			} elseif (Model::factory('users')->exists($field->value, $id)) {
				$field->error(Text::DUPLICATE_KEY);
			}
		}
		$roles = array();
		foreach (Acl::getInstance()->roles() as $role => $parent) {
			if ($role == 'root') {
				continue;
			}
			$roles[$role] = ucfirst(strtolower(preg_replace('|([A-Z])|', ' \1', $role)));
		}
		$form->select('role', $roles, 'Role')->required();
		if (!$id) {
			$form->html('passwordReq', '', 'Password must be atleast 5 characters long')->phantom();
			$form->password('password', 'Password')->attribute('size', 24)
				->rule('maxLength', 32)->rule('minLength', 5)->rule('required');
			$form->password('password2', 'Confirm Password')->attribute('size', 24)
				->rule('required')->callback('passwordCheck')->bunched();
			//$form->checkbox('emailUser', '', 'Email new password to user', 1);
		}
		function passwordCheck($field) {
			if ($field->form->elements['password']->value != $field->value) {
				$field->error('Passwords are not match');
			}
		};
		$form->submit('submit', 'Add');
		if ($id) {
			$form->elements['submit']->value = 'Save';
			$user = $this->model->getUser($id);
			$form->loadValues($user);
		}
		if ('POST' == Request::$method) {
			if ($form->validate()) {
				$values = $form->getValues();
				if ($id) {
					if (!isset($roles[$values['role']])) {
						throw new ForbiddenException('Role does not exist');
					}
					$this->model->update($values, $id);
					
				} else {
					unset($values['password2']);
					$emailUser = false;
					if (isset($values['emailUser'])) {
						if ($values['emailUser'] == 1) {
							$emailUser = true;
						}
						unset($values['emailUser']);
					}
					if (isset($values['role']) ? !isset($roles[$values['role']]) : true) {
						throw new ForbiddenException();
					}
					$userId = $this->model->insert($values);
					if ($emailUser) {
						$this->emailPassword($userId, $values['password']);
					}
				}
				$this->response->redirect(Request::$controller);
			}
		}
		$this->template->content = new View('admin/users/form', array('form' => $form));
	}

	public function actionPassword($id = null)
	{
		$this->template->title = 'Edit user profile';
		$form = new Form('password', 'Change password');
		$form->attributes['autocomplete'] = 'off';
		$form->labelWidth = '150px';
		$form->password('password', 'New password')->attribute('size', 24)
			->attribute('maxlength', 32)->rule('minLength', 5)->rule('required');
		$form->password('password2', 'Confirm Password')->attribute('size', 24)
			->rule('required')->callback('passwordCheck')->bunched();
		//$form->checkbox('emailUser', '', 'Email new password to user', 1);
		function passwordCheck($field) {
			if ($field->form->elements['password']->value != $field->value) {
				$field->error('Passwords are not match');
			}
		};
		$form->submit('submit', 'Update');
		$user = $this->model->getUser($id);
		if ('POST' == Request::$method) {
			if ($form->validate()) {
				$values = $form->getValues();
				unset($values['password2']);
				if ($values['password'] == '') {
					unset($values['password']);
				}
				if (isset($values['emailUser'])) {
					if ($values['emailUser'] == 1) {
						$this->emailPassword($id, $values['password']);
					}
					unset($values['emailUser']);
				}
				$this->model->update($values, $id);
				$this->template->info = Text::CHANGES_SAVED;
				$this->response->redirect(Request::$controller);
			}
		}
		$this->template->content = new View('admin/users/form', array('form' => $form));
	}

	private function emailPassword($userId, $password)
	{
		$user = $this->model->getUser($userId);
		$msg = '';
		$msg .= 'From: ' . $this->settings['title'] . "\n";
		$msg .= 'Hello, ' . $user['fullName'] . "\n";
		$msg .= 'You can login to ' . Url::site() . ' using this login and password:' . "\n";
		$msg .= 'Login: ' . $user['name'] . "\n";
		$msg .= 'Password: ' . $password . "\n\n";
		$msg .= 'Have a nice day!';
		Mail::sendMail($user['email'], 'Login information to ' . $this->settings['title'], $msg);
	}

	public function actionRemove($id)
	{
		$currentUser = Auth::getInstance()->getIdentity();
		$user = $this->model->getUser($id);
		if ($user['role'] != 'root' && $user['id'] != $currentUser['id']) {
			Model_Table::instance('users')->delete($id);
		} else {
			throw new Exception('You can\'t delete yourself');
		}
		$this->response->redirect(Request::$controller);
	}
}